import { FC, useState, useEffect, useRef } from 'react';
import {
  Divider,
  Space,
  Form,
  Table,
  Button,
  message,
  Spin,
  Pagination,
  Input,
  Modal,
  Select,
} from 'antd';
import { Link } from 'react-router-dom';
import { useCurrentSize } from '@src/utils/useIndex';
import { DictionarySearchForm } from './dictionarySearchForm';
import {
  confSysCodeGetByCodeTypeAPI,
  confSysCodeSaveOrUpdateAPI,
  getDirListAPI,
} from '@src/apis/systemManagement';
export const SystemDictionary: FC = () => {
  const [dirTypeList, setDirTypeList] = useState<any>([]);
  const searchFormRef = useRef<any>();

  useEffect(() => {
    getDirListAPI().then((result: any) => {
      setDirTypeList(result.data || []);
    });
  }, []);
  // useEffect(() => {
  //   //默认进来不查询页面
  //   console.log('默认进来查询页面');
  //   getPageList();
  //   return () => {};
  // }, []);
  const { pageInfo, setPageInfo } = useCurrentSize();
  const { Option } = Select;
  const pageThis: any = useRef({ whyPopShow: 'add', currentLine: {}, modalTitle: '新增' });
  const [addPlanyForm] = Form.useForm();
  const [addPlanyShow, setAddPlanyShow] = useState<boolean>(false);
  const [pageListData, setPageListData] = useState<any>([]);
  const [colums] = useState<any>([
    {
      title: '字典名称',
      dataIndex: 'codeName',
      key: 'codeName',
      width: 100,
    },
    {
      title: '字典值',
      dataIndex: 'code',
      key: 'code',
      width: 100,
    },
    {
      title: '字典类型名称',
      dataIndex: 'codeTypeName',
      key: 'codeTypeName',
      width: 100,
    },
    {
      title: '字典类型值',
      dataIndex: 'codeType',
      key: 'codeType',
      width: 100,
    },
    {
      title: '操作',
      key: 'Actions',
      width: 100,
      fixed: 'right',
      render: (text: any, record: any) => (
        <Space split={<Divider type="vertical" />}>
          <Button
            type="link"
            onClick={() => {
              pageThis.current.whyPopShow = 'edit';
              pageThis.current.modalTitle = '编辑';
              pageThis.current.currentLine = record;
              addPlanyForm.setFieldsValue({
                code: record.code,
                codeName: record.codeName,
                codeType: ajaxParams.current.codeType,
              });
              setAddPlanyShow(true);
            }}
          >
            修改
          </Button>
          <Button
            type="link"
            onClick={() => {
              Modal.confirm({
                title: '删除',
                content: '确定删除？',
                okText: '确认',
                cancelText: '取消',
                onOk() {
                  return new Promise((resolve: any, reject: any) => {
                    alert(JSON.stringify(record));
                    resolve();
                    // setTimeout(Math.random() > 0.5 ? resolve : reject, 1000);
                  });
                },
              });
            }}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ]);
  const [tableLoading, setTableLoading] = useState<boolean>(false);
  const ajaxParams: any = useRef({});
  const searchBtnF = (formValue: any) => {
    console.log('点击了搜索', formValue);
    ajaxParams.current = formValue;
    getPageList(1, ajaxParams.current.size || pageInfo.size);
  };
  const getPageList = (current?: any, size?: any) => {
    let canshu: any = {
      ...ajaxParams.current,
    };
    canshu.current = current || ajaxParams.current.current || pageInfo.current;
    canshu.size = size || ajaxParams.current.size || pageInfo.size;
    setTableLoading(true);
    confSysCodeGetByCodeTypeAPI(canshu)
      .then((result: any) => {
        console.log(result);
        if (
          /*如果后台返回值没有数据 并且并非是在第一页*/
          result.data?.model?.length === 0 &&
          result.data?.current !== 1
        ) {
          getPageList(1, canshu.size);
          return;
        }
        setPageListData(result.data);
        setPageInfo({
          current: result.data.current,
          size: result.data.size,
        });
      })
      .catch((err: any) => {
        console.log(err);
      })
      .finally(() => {
        setTableLoading(false);
      });
  };
  const indexAddF = () => {
    pageThis.current.whyPopShow = 'add';
    pageThis.current.modalTitle = '新增';
    pageThis.current.currentLine = {};
    addPlanyForm.resetFields();
    setAddPlanyShow(true);
  };
  const onOk = () => {
    addPlanyForm.validateFields().then((values: any) => {
      console.log(values);
      //找到业务类型的元数据
      let codeTypeObj: any = dirTypeList.filter((item: any) => {
        return item.codeType === values.codeType;
      })[0];
      let canshu: any = { ...values, codeTypeName: codeTypeObj.codeTypeName };
      if (pageThis.current.currentLine.id) {
        canshu = {
          id: pageThis.current.currentLine.id,
          codeTypeName: pageThis.current.currentLine.codeTypeName,
          ...values,
        };
      }
      confSysCodeSaveOrUpdateAPI(canshu).then((result: any) => {
        console.log(result);
        pageThis.current.currentLine = {};
        setAddPlanyShow(false);
        //更改筛选条件为刚刚保存的，并且查询数据
        searchFormRef.current.searchFormInit({
          codeType: codeTypeObj.codeType,
        });
        ajaxParams.current.codeType = codeTypeObj.codeType;
        getPageList(1);
      });
    });
  };

  const paginationChange = (pageNo: number, pageSize: any) => {
    console.log('pageNo=' + pageNo, 'pageSize=' + pageSize);
    getPageList(pageNo, pageSize);
  };

  const showTotal = () => {
    return `${pageListData?.total || 0}条记录`;
  };
  return (
    <div className="pageBox">
      <Spin spinning={tableLoading} delay={100}>
        <DictionarySearchForm
          ref={searchFormRef}
          dirTypeList={dirTypeList}
          searchBtnF={searchBtnF}
          indexAddF={indexAddF}
        />
        <div className="anTableBox margT10">
          <Table
            size={'small'}
            scroll={{ x: '100%' }}
            dataSource={pageListData.model || []}
            columns={colums}
            rowKey={(record) => record.id || Math.random()}
            pagination={false}
          />
          <Pagination
            hideOnSinglePage={true}
            style={{ textAlign: 'right', margin: '10px 0 0 0' }}
            size="small"
            current={pageInfo.current}
            pageSize={pageInfo.size}
            total={pageListData?.total || 0}
            showTotal={showTotal}
            onChange={paginationChange}
            showSizeChanger
            showQuickJumper
          />
        </div>
      </Spin>
      <Modal
        title={pageThis.current.modalTitle}
        destroyOnClose={true}
        visible={addPlanyShow}
        onCancel={() => {
          setAddPlanyShow(false);
        }}
        onOk={onOk}
      >
        <div>
          <Form
            className="anTopSearchForm fff pad20"
            form={addPlanyForm}
            name="maitainSearcher"
            labelCol={{
              md: { span: 6 },
            }}
            wrapperCol={{
              md: { span: 16 },
            }}
          >
            <Form.Item label="字典类型" name="codeType" rules={[{ required: true }]}>
              <Select
                disabled={pageThis.current.whyPopShow === 'edit'}
                showSearch
                allowClear
                optionFilterProp="children"
                placeholder="请选择"
              >
                {dirTypeList?.map((item: any, index: number) => {
                  return (
                    <Option
                      title={item.codeTypeName + '-' + item.codeType}
                      key={item.codeType}
                      value={item.codeType}
                    >
                      {item.codeTypeName}
                    </Option>
                  );
                })}
              </Select>
            </Form.Item>
            <Form.Item label="字典名称" name="codeName" rules={[{ required: true }]}>
              <Input placeholder="请输入" />
            </Form.Item>
            <Form.Item label="字典值" name="code" rules={[{ required: true }]}>
              <Input placeholder="请输入" />
            </Form.Item>
          </Form>
        </div>
      </Modal>
    </div>
  );
};
